package cn.kgc.javaweb.servlet;


import cn.kgc.javaweb.entity.Student;
import cn.kgc.javaweb.servlet.BaseServlet;
import com.alibaba.fastjson.JSON;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;

/**
 * @author: mosin
 * @version: v1.0  2022/6/23
 */
@WebServlet("/user")
public class UserServlet extends BaseServlet {



    protected void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置请求对象编码格式
        req.setCharacterEncoding("utf-8");

        String username = req.getParameter("username");
        String password = req.getParameter("password");

        if("admin".equals(username)&& "12345".equals(password)){ // 跳转主页显示学生信息

            //  查询数据库
            ArrayList<Student> students = new ArrayList<>();
            for (int i = 0; i < 10; i++) {
                Student student = Student.builder().birth(new Date()).age(20 + i).stuName("张" + i).stuNo("202000" + i).build();
                students.add(student);
            }

            // index.jsp   转发  重定向  session
            HttpSession session = req.getSession();
            session.setAttribute("students", students);
            //  req.getContextPath()  项目虚拟路径  localhost:8080/javaweb/index.jsp
            //resp.sendRedirect(req.getContextPath()+"/index.jsp");
            resp.sendRedirect(req.getContextPath()+"/StudentList.jsp");

        }else{  // 跳转到登录页  显示提示信息

            req.setAttribute("info", "用户名或密码错误");
            req.getRequestDispatcher("login.jsp").forward(req, resp);

        }


    }

    protected void checkUserName(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        // 验证同步和异步的效果
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        req.setCharacterEncoding("utf-8");
        String username = req.getParameter("username");

        HashMap<String, Object> map = new HashMap<>();

        if("admin".equals(username)){ //用户名不可用

            map.put("code", 500);
            map.put("msg", "用户名已被占用");

        }else{

            map.put("code", 200);
            map.put("msg", "用户名可用");

        }

        resp.setCharacterEncoding("utf-8");
        resp.setContentType("application/json;charset=utf-8");
        PrintWriter writer = resp.getWriter();

        String s = JSON.toJSONString(map);

        writer.write(s);
        writer.close();


    }

}
